//
//  LoginVC.m
//  TuYouAPP
//
//  Created by L on 14-2-27.
//
//

#import "LoginVC.h"
#import <AVOSCloud/AVOSCloud.h>
#import <AVOSCloudSNS/AVOSCloudSNS.h>
#import "Util.h"
#import <AVOSCloudSNS/AVUser+SNS.h>
#import "JSONKit.h"
#import "PublishVC.h"
#import "DataModel.h"
@interface LoginVC ()

@end

@implementation LoginVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
#define P_X @"tuyou_auto_psw"
-(void)logOK
{
    if( _tagVC )
    {
        NSMutableArray* t = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
        [t removeLastObject];
        [t addObject:_tagVC];
        [self.navigationController setViewControllers:t animated:YES];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)loginBtn:(id)sender {
    
    AVUser* usera = [AVUser user];
    
    [usera setObject:[Util GetUUID] forKey:@"username"];
    [usera setObject:@"tuyou_auto_psw" forKey:@"password"];
    [usera setObject:_userName.text forKey:@"userDisplayName"];
    [usera setObject:[NSNumber numberWithInt:[_userSex.text isEqualToString:@"男"]?2:1]  forKey:@"Sex"];
    
    //直接注册一个新的
    [usera signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if( succeeded )
        {//成功
            [TYUser updateUser];
            [self logOK];
        }
        else
        {//失败
            [AVUser logInWithUsernameInBackground:[Util GetUUID] password:@"tuyou_auto_psw" block:^(AVUser *user, NSError *error) {
                
                if( user )
                {
                    [user setObject:_userName.text forKey:@"userDisplayName"];
                    [user setObject:[NSNumber numberWithInt:[_userSex.text isEqualToString:@"男"]?2:1]  forKey:@"Sex"];
                    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if( succeeded )
                        {
                            [TYUser updateUser];
                            [self logOK];
                        }
                        else
                        {
                            
                            [SVProgressHUD showErrorWithStatus:@"登陆失败"];
                        }
                        
                    }];;
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:@"登陆失败"];
                }
                
            }];
        }
        
    }];
}

//然后在登录 SNS 成功回调后loginWithAuthData:block, 这样会用当前的 SNS 用户来尝试登录获取 AVUser 信息, 如果 AVUser 不存在, 系统会自动创建新用户并返回, 如果已经存在, 则直接返回该用户.
//这里不能使用自动创建的,必须自己创建,机器账户,并且机器账户没有绑定微博就是那个账户,和这个微博绑定,如果那个机器账户已经绑定了,并且不是这个微博,那这个账户就新的微博账户,才用自动创建的账户
- (IBAction)sinaLogin:(id)sender {
    
    [GInfo shareClient].isAVOSCloud = YES;

    [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:SINA_KEY andAppSecret:SINA_SEC andRedirectURI:REDI_URI];

    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if( object )
        {//
            [self moreDeal:object];
        }
        else
        {//失败
            [SVProgressHUD showErrorWithStatus:@"新浪登陆失败"];
        }
    } toPlatform:AVOSCloudSNSSinaWeibo];
}
-(void)moreDeal:(id)weiboAuthData
{
     NSString* uidwb = [[weiboAuthData objectForKey:@"raw-user"] objectForKey:@"idstr"];
    
    AVQuery* query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"weibo_uid" equalTo:uidwb];
    [query selectKeys:@[@"authData",@"weibo_uid"]];
    
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *objectav, NSError *errorav) {
        if(errorav &&  [[errorav.userInfo objectForKey:@"code"] intValue] != 101 )
        {//出错了,
            [SVProgressHUD showErrorWithStatus:@"登陆出现异常"];
            return ;
        }
        else
        if( objectav )
        {//如果有这个UID,说明这个微博账号已经被人绑定,
            
            [self justNewWeiBoLogin:weiboAuthData];
        }
        else
        {//如果这个微博账户没有被人绑定过,那就和这个机器UUID账户绑定,
            
            [AVUser logInWithUsernameInBackground:[Util GetUUID] password:@"tuyou_auto_psw" block:^(AVUser *userl, NSError *error) {
                
                if( userl )
                {//有这个机器,
                    NSString* maybehaveuid = [userl objectForKey:@"weibo_uid"];
                    if( maybehaveuid == nil )
                    {//如果这个用户没有绑定,,就绑定,
                        [userl addAuthData:weiboAuthData block:^(AVUser *user, NSError *error) {
                            
                            if( user )
                            {
                                [user setObject:uidwb forKey:@"weibo_uid"];
                                [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                                    if( succeeded )
                                    {
                                        [LoginVC updateUserWeiBoInfo:weiboAuthData user:user];
                                        [self logOK];
                                    }
                                    else
                                    {
                                        [SVProgressHUD showErrorWithStatus:@"登陆失败"];
                                    }
                                    
                                }];
                            }
                            else
                            {
                                [SVProgressHUD showErrorWithStatus:@"绑定账户失败"];
                            }
                        }];
                    }
                    else
                    {//如果这个用户绑定了,
                        if( [maybehaveuid isEqualToString:uidwb] )
                        {//如果用户绑定的就是这个微博,更新下信息就好了
                            [LoginVC updateUserWeiBoInfo:weiboAuthData user:userl];
                            [self logOK];
                        }
                        else
                        {//如果绑定的不是这个,那么不能替换绑定,直接登陆,生成默认的,
                            [self justNewWeiBoLogin:weiboAuthData];
                        }
                    }
                }
                else
                {
                    //没有,先创建一个再绑定,
                    [self createUUIDUserAndBweibo:weiboAuthData];
                }
                
            }];
        }
    }];

}
//生成UUID账户,然后绑定这个微博
-(void)createUUIDUserAndBweibo:(id)weiboAuthData
{
    AVUser* usernew = [AVUser user];
    [usernew setObject:[Util GetUUID] forKey:@"username"];
    [usernew setObject:@"tuyou_auto_psw" forKey:@"password"];
    [usernew setObject:[[weiboAuthData objectForKey:@"raw-user"] objectForKey:@"idstr"] forKey:@"weibo_uid"];
    [usernew signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
       
        if ( succeeded )
        {
            AVUser* okuser =[AVUser currentUser];
            [okuser addAuthData:weiboAuthData block:^(AVUser *user, NSError *error) {
                
                if( user )
                {
                    [LoginVC updateUserWeiBoInfo:weiboAuthData user:user];
                    [self logOK];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:@"绑定用户失败"];
                }
            }];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:@"创建用户失败"];
        }
        
    }];
}
//新的微博账户登陆,本本地账户以及本地绑定微博无关
-(void)justNewWeiBoLogin:(id)weiboAuthData
{
    [AVUser loginWithAuthData:weiboAuthData block:^(AVUser *user, NSError *error) {
        
        if( user != nil )
        {//成功
            //成功
            [LoginVC updateUserWeiBoInfo:weiboAuthData user:user];
            [self logOK];
        }
        else
        {//失败
            [SVProgressHUD showErrorWithStatus:@"登陆失败"];
        }
        
    }];
}

//更新
+(void)updateUserWeiBoInfo:(id)object user:(AVUser*)user
{
    //获取资料,昵称,性别
    NSString* userdisname = [[object objectForKey:@"raw-user"] objectForKey:@"screen_name"];
    NSString* mfn = [[object objectForKey:@"raw-user"] objectForKey:@"gender"];
    NSString* userpointinfo = [[object objectForKey:@"raw-user"] objectForKey:@"location"];
    NSString* usersmallpic = [[object objectForKey:@"raw-user"] objectForKey:@"avatar_large"];
    NSString* uid = [[object objectForKey:@"raw-user"] objectForKey:@"idstr"];
    
    if( usersmallpic )
        [user setObject:usersmallpic forKey:@"bigHeadImgURL"];
    
    if( usersmallpic )
        usersmallpic = [usersmallpic stringByReplacingOccurrencesOfString:@"/180/" withString:@"/50/"];
    if( userdisname )
        [user setObject:userdisname forKey:@"userDisplayName"];
    
    if( mfn )
        [user setObject:[NSNumber numberWithInt:[mfn isEqualToString:@"m"]?2:1] forKey:@"Sex"];
    
    if( userpointinfo )
        [user setObject:userpointinfo forKey:@"userPointInfo"];
    
    if( usersmallpic )
        [user setObject:usersmallpic forKey:@"HeadImgURL"];
    
    if( uid )
        [user setObject:uid forKey:@"weibo_uid"];
    
    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if( succeeded )
        {
            [TYUser updateUser];
        }
        
    }];
}

- (IBAction)chooseSex:(id)sender {
    [self.userName resignFirstResponder];
    UIActionSheet *ac = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
    ac.tag = 1002;
    [ac showInView:[self.view window]];

}
-(void)rightBtnTouched:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];

}
- (IBAction)canceled:(id)sender {
}
-(void)loadView
{
    self.isBackBtn = YES;

    [super loadView];
}
- (void)viewDidLoad
{
    self.mPageName = @"登录";
    [super viewDidLoad];
    self.RightBarTitle = @"取消";
    self.Title = @"登录";
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"username" equalTo:[Util GetUUID]];
    [query whereKeyDoesNotExist:@"userDisplayName"];
    [query countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
        if (number==1) {
            [UIView animateWithDuration:0.2 animations:^{
                self.botView.hidden = NO;

            }];
        }
        else
        {
            self.botView.hidden = YES;
        }
    }];
 
    // Do any additional setup after loading the view from its nib.
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [AVOSCloudSNS handleOpenURL:url];

    
}
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    
    NSLog(@"handleOpenURL");

    
    return [AVOSCloudSNS handleOpenURL:url];
    
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
 
        if (buttonIndex == 0) {
            self.userSex.text = @"男";
        }
        else
        {
            self.userSex.text = @"女";
        }
    
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
